package ljl.alg.wangzheng_camp.round1.dp;

import java.util.List;

public class _120_min_sum_triangle {
    
    /**
    * 这个是状态压缩版
    * */
    public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.get(triangle.size() - 1).size();
        int[] dp = new int[n];
        dp[0] = triangle.get(0).get(0);
        for (int i = 1; i < n; i++) {
            List<Integer> level = triangle.get(i);
            dp[i] = dp[i - 1] + level.get(i);
            for (int j = i - 1; j > 0 ; j--) {
                dp[j] = Math.min(dp[j], dp[j - 1]) + level.get(j);
            }
            dp[0] += level.get(0);
        }
        int min = dp[0];
        for (int i : dp) {
            if (i < min) min = i;
        }
        return min;
    }
    
    /**
     * 正常版也得写写，不然怕你是背的压缩版
     * */
    public int minimumTotal2(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[][] dp = new int[n][n];
        dp[0][0] = triangle.get(0).get(0);
        for (int i = 1; i < n; i++) {
            List<Integer> level = triangle.get(i);
            dp[i][0] = dp[i - 1][0] + level.get(0);
            for (int j = 1; j < i ; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - 1]) + level.get(j);
            }
            dp[i][i] = dp[i - 1][i - 1] + level.get(i);
        }
        int min = dp[n - 1][0];
        for (int i : dp[n - 1]) {
            if (i < min) min = i;
        }
        return min;
    }
    
    /**
     * 从下往上遍历
     * 官方题解说了可以这么遍历，但是没说怎么写
     * 这是一个玩家贡献的解法，很不凑
     * */
    public int minimumTotal3(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[] dp = triangle.get(n - 1).stream().mapToInt(Integer::valueOf).toArray();
        for (int i = n - 2; i >= 0; i--) {
            for (int j = 0; j <= i; j++) {
                dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
            }
        }
        return dp[0];
    }
}
